package com.item.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.base.util.DateUtil;
import com.base.util.FileExportUtils;


import com.aliyun.openservices.ClientConfiguration;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ListObjectsRequest;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.OSSObjectSummary;
import com.aliyun.openservices.oss.model.ObjectListing;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.base.CoreConstants;
import com.base.util.SpringContextUtil;
import com.item.dao.model.Essence;
import com.item.dao.model.EssenceNew;
import com.item.dao.model.MediaFile;
import com.item.dao.model.MediaFileExample;
import com.item.service.EssenceAuthorService;
import com.item.service.EssenceNewService;
import com.item.service.EssenceService;
import com.item.service.MediaFileService;

public class MyOssClient {
	private static String OSS_KEY = CoreConstants.OSS_KEY;
	private static String OSS_SECRET = CoreConstants.OSS_SECRET;
	private static String OSS_ENDPOINT  = CoreConstants.OSS_ENDPOINT;
	private static OSSClient client;
	
	private final static String BASE_PATH = CoreConstants.FILE_PATH + "/temp/";
	
	private MediaFileService fser;
	private EssenceNewService essenceser;
	private EssenceAuthorService  authorService;
//	private final static String BASE_PATH = "/home/nju/zsnd/temp/";
	static {//初始化
		MyOssClient.initial();
	}
	
	public OSSClient getClient(){
		return this.client;
	}
	/**
	 * 初始化配置参数
	 */
	private static void initial() {
		ClientConfiguration conf = new ClientConfiguration();
		
		// 设置HTTP最大连接数为10
		conf.setMaxConnections(100);

		// 设置TCP连接超时为5000毫秒
		conf.setConnectionTimeout(5000);

		// 设置最大的重试次数为2
		conf.setMaxErrorRetry(2);

		// 设置Socket传输数据超时的时间为10000毫秒
		conf.setSocketTimeout(10000);
		
		client =  new OSSClient(OSS_ENDPOINT, OSS_KEY, OSS_SECRET, conf);
	}
	
	/**
	 * 写入文件
	 * @param bucketName
	 * @param key
	 * @param data
	 * @throws IOException
	 */
	public static boolean putObject(String key, byte[] data, String bucketName) throws IOException {
	    // 获取指定文件的输入流
	    InputStream content = new ByteArrayInputStream(data);

	    // 创建上传Object的Metadata
	    ObjectMetadata meta = new ObjectMetadata();

	    // 必须设置ContentLength
	    meta.setContentLength(data.length);
	    setMeta(meta, key); //设置http头
	    
	    // 上传Object.
	    PutObjectResult result = client.putObject(bucketName, key, content, meta);
	    
	    return result != null;
	}
	
	/**
	 * 写入文件
	 * @param bucketName
	 * @param key
	 * @param data
	 * @throws IOException
	 */
	public static boolean putObject(String key, InputStream in, String bucketName) throws IOException {
	    // 创建上传Object的Metadata
	    ObjectMetadata meta = new ObjectMetadata();

	    // 必须设置ContentLength
	    meta.setContentLength(in.available());
	    setMeta(meta, key); //设置http头
	    
	    // 上传Object.
	    PutObjectResult result = client.putObject(bucketName, key, in, meta);
	  
	    return result != null;
	}
	
	/**
	 * 获取文件
	 * @param bucketName
	 * @param key
	 * @throws IOException
	 */
	public static InputStream getObjectStream(String key, String bucketName) throws IOException {
	    // 获取Object，返回结果为OSSObject对象
	    OSSObject object = null;
	    InputStream objectContent = null;
	    // 获取Object的输入流
	    try {
	    	object = client.getObject(bucketName, key);
	    	objectContent = object.getObjectContent();
	    } catch(Throwable e) {//异常close连接，正确不关闭
	    	if(objectContent != null) {
	    		objectContent.close();
	    	}
	    	return null; //返回空
	    }

	    return objectContent;
	}

	/**
	 * 获取文件
	 * @param bucketName
	 * @param key
	 * @throws IOException
	 */
	public static byte[] getObject(String key, String bucketName) throws IOException {
	    // 获取Object，返回结果为OSSObject对象
	    OSSObject object = null;
	    byte[] data = null;
	    InputStream objectContent = null;
	    
	    // 获取Object的输入流
	    try {
	    	object = client.getObject(bucketName, key);
	    	
	    	objectContent = object.getObjectContent();
	    
	    	data = getByteFromFile(key, objectContent);
	    	
	    	objectContent.read(data);
	    } catch(Exception e) {
	    	return null; //返回空
	    } finally {
	    	if(objectContent != null)
	    		objectContent.close();
	    }
	    return data;
	}
	
	public static BufferedImage getObjectImg(String key, String bucketName) throws IOException {
		OSSObject object = null;
	    // 获取Object的输入流
		BufferedImage bimg = null;
		InputStream objectContent = null;
	    try {
	    	object = client.getObject(bucketName, key);
	    	objectContent = object.getObjectContent();
	    	bimg = ImageIO.read(objectContent);
	    } catch(Throwable e) {
	    	return null; //返回空
	    } finally {
	    	if(objectContent != null)
	    		objectContent.close();
	    }

	    return bimg;
	}
	
//	public static void listObjects() {
//	    // 获取指定bucket下的所有Object信息
//	    ObjectListing listing = client.listObjects(BUCKET_NAME);
//
//	    // 遍历所有Object
//	    for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
//	        System.out.println(objectSummary.getKey());
//	    }
//	}
	
	public static byte[] getByteFromFile(String filename, InputStream in) throws IOException {
		byte[] data = null;
		
		File file = new File(BASE_PATH + "/" + filename);
		if(!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		FileOutputStream fout = new FileOutputStream(file);
		byte[] buff = new byte[1024];
		int len = 0;
		while((len = in.read(buff)) > 0) {
			fout.write(buff, 0, len);
		}
		fout.close();
		data = FileUtils.readFileToByteArray(file);
//		System.out.println(data.length);
		if(file.exists())
			file.delete();
		return data;
	}
	
	public static void deleteObject(String key, String bucketName) {
		client.deleteObject(bucketName, key);
	}
	
	
	public static ObjectListing  listObject(String prefix, String bucketName) {
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

		// 设置参数
		listObjectsRequest.setPrefix(prefix);

		return client.listObjects(listObjectsRequest);
	}
	
	/**
	 * 根据文件名设置meta属性
	 * @param meta
	 * @param key
	 */
	public static void setMeta(ObjectMetadata meta, String key) {
		key = key.toLowerCase(); //全部转成小写
		if(key.endsWith("html")) {
			meta.setContentType("text/html");
			meta.setContentEncoding("utf-8");
			meta.setCacheControl("max-age=900"); //缓存时间
		}
		if(key.endsWith("jpeg") || key.endsWith("jpg")) {
			meta.setContentType("image/jpeg");
			meta.setCacheControl("max-age=31536000");
		}
		if(key.endsWith("png")) {
			meta.setContentType("image/png");
			meta.setCacheControl("max-age=31536000");
		}
		if(key.endsWith("gif")) {
			meta.setContentType("image/gif");
			meta.setCacheControl("max-age=31536000");
		}
		if(key.endsWith("mp3")) {
			meta.setContentType("audio/mp3");
			meta.setCacheControl("max-age=31536000");
		}
		if(key.endsWith("avi")) {
			meta.setContentType("video/avi");
			meta.setCacheControl("max-age=31536000");
		}
		if(key.endsWith("js")) {
			meta.setContentType("application/x-javascript");
			meta.setCacheControl("max-age=600");
		}
		if(key.endsWith("css")) {
			meta.setContentType("text/css");
			meta.setCacheControl("no-cache");
		}
	}
	
	public static Map<String,Integer> mediaTypes = new HashMap<String,Integer>();
	{
		mediaTypes.put("mp4",1);
		mediaTypes.put("avi",1);
		mediaTypes.put("flv",1);
		mediaTypes.put("mp3", 2);
		mediaTypes.put("pdf", 3);
		mediaTypes.put("docx", 3);
		mediaTypes.put("rar",3);
		mediaTypes.put("zip",3);
		mediaTypes.put("doc",3);
	}
	
	
	
	
	
	public void test()throws Exception{
		if(fser == null){
			fser = SpringContextUtil.getBean(MediaFileService.class);
		}
		if(essenceser == null){
			essenceser = SpringContextUtil.getBean(EssenceNewService.class);
		}
		if(authorService == null){
			authorService = SpringContextUtil.getBean(EssenceAuthorService.class);
		}
		Matcher mat = Pattern.compile("(.*)（(.*)）-(.*)").matcher("");
		int count = 0;
		int countFile = 0;
		List<String> sources = new ArrayList<String>();
		sources.add("兜子");
		sources.add("乐天");
		sources.add("开怀大笑");
		sources.add("风中年华");
		sources.add("我是MM");
		sources.add("TRACY");
		sources.add("点点");
		
		//先测试英语
		StringBuilder path = new StringBuilder();
		String initPath = "kaoyanbiji/math/";
		ListObjectsRequest request = new ListObjectsRequest("zsnd-web-file");
		request.setPrefix(initPath);
		request.setDelimiter("/");
		ObjectListing listing = client.listObjects(request);
		Random rand = new Random();
		for(String common : listing.getCommonPrefixes()){
			//再新建一个rqeust，这是第二级目录
			ListObjectsRequest requestSecond = new ListObjectsRequest("zsnd-web-file");
			String essenceName = common.split("/")[2];
			mat.reset(essenceName);
			if(mat.find()){
				String teacher = mat.group(1);
				String depart = mat.group(2);
				String name = mat.group(3);
				System.out.println(teacher + "  " + depart + "   " + name);
				
						
			}
				
				
			
		}
//		MediaFile file = new MediaFile();
//		file.setFileBelong("");
//		file.setFileCreater("");
//		file.setFileCreatetime(new Date());
//		file.setFileMd5("");
//		file.setFileMinitype("");
//		file.setFileName("测试");
//		file.setFilePath("");
//		file.setFileSize(1000L);
//		file.setFileState(1);
//		fser.insert(file);
//		System.out.println("id " + file.getFileId());
		
	}
	
	public static void main(String[] args) throws Exception {
		MyOssClient test = new MyOssClient();
		test.test();
	}
}
